import React, { useEffect, useState } from 'react'
import AOS from 'aos'
import 'aos/dist/aos.css'
import { getBlogListXhr } from '~/api/index'
import { DEFAULT_AVATAR } from '~/const/index'
import { BLOG_TYPE_MAP } from '~/const/index'
import dayjs from 'dayjs'
import { useNavigate } from 'react-router-dom'
import AIChat from '~/components/AIChat'
import { hasLogin } from '~/utils/cookie'
import AuthModal from '~/components/AuthModal'
import Toast from '~/utils/toast'

interface ArticleProps {
  item: any
  delay?: number
}

const Article: React.FC<ArticleProps> = ({ item, delay = 0 }) => {
  const navigate = useNavigate()
  return (
    <article
      className="glass-card p-6 hover-scale cursor-pointer"
      data-aos="fade-up"
      data-aos-delay={delay.toString()}
      onClick={() => {
        navigate(`/article/${item.id}`)
      }}
    >
      <div className="flex items-center justify-between mb-4">
        <span className="text-blue-400">
          #{item?.category ? BLOG_TYPE_MAP?.[item?.category] || '技术' : '技术'}
        </span>
        <span className="text-xs text-gray-400 ml-2">
          <i className="ri-eye-line mr-1"></i> 阅读 {item.views || 0}
        </span>
      </div>
      <h2 className="text-2xl font-bold mb-4 truncate">{item.title}</h2>
      {item.content && item.content.replace(/<[^>]+>/g, '').trim() ? (
        <p className="text-gray-500 dark:text-gray-300 mb-4 line-clamp-2">
          {item.content.replace(/<[^>]+>/g, '').slice(0, 120)}...
        </p>
      ) : (
        <div className="h-[18px] mb-4"></div>
      )}
      <div className="flex items-center justify-between text-sm text-gray-400">
        <div className="flex items-center">
          <i className="ri-time-line mr-2"></i>
          <span>
            {item?.createdAt ? dayjs(item.createdAt).format('YYYY-MM-DD') : ''}
          </span>
        </div>
        <div className="flex items-center ml-4">
          <img
            src={item?.authorAvatar || DEFAULT_AVATAR}
            alt="avatar"
            className="w-6 h-6 rounded-full mr-2"
          />
          <span className="text-gray-600">
            {item?.authorName || '不知名网友'}
          </span>
        </div>
      </div>
    </article>
  )
}

const HomePage: React.FC = () => {
  const [newBlogList, setNewBlogList] = useState<any[]>([])
  const [isOpenAi, setIsOpenAi] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)
  useEffect(() => {
    AOS.init({
      duration: 800,
      once: true,
    })
  }, [])
  useEffect(() => {
    getBlogListXhr({
      page: 1,
      pageSize: 6,
    }).then((res) => {
      setNewBlogList(res.data.list)
    })
  }, [])
  const navigate = useNavigate()
  const handleOnpenAi = () => {
    if (hasLogin()) {
      setIsOpenAi(true)
    } else {
      Toast.info('请先登录')
      setIsModalOpen(true)
    }
  }

  return (
    <div>
      {/* 主页横幅 */}
      <header className="pt-12 pb-4 px-4">
        <div className="container text-center" data-aos="fade-up">
          <h3 className="text-4xl font-bold mb-6">🎉欢迎来到七安的博客🎉</h3>
          <p className="text-xl text-gray-500 dark:text-gray-300 mb-8">
            分享技术，记录生活
          </p>
          <button
            className="bg-blue-500 hover:bg-blue-600 text-white px-8 py-3 rounded-full transition-colors flex items-center justify-center space-x-2 inline-flex"
            onClick={() => navigate(`/articles`)}
          >
            <i className="ri-book-open-line"></i>
            <span>开始阅读</span>
          </button>
          <button
            className="bg-purple-500 hover:bg-purple-600 text-white px-8 py-3 rounded-full transition-colors flex items-center justify-center space-x-2 inline-flex ml-2"
            onClick={() => handleOnpenAi()}
          >
            <i className="ri-robot-line"></i>
            <span>AI 助手</span>
          </button>
        </div>
      </header>

      {/* 文章卡片区 */}
      <section className="py-8 px-6">
        <div className="container grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
          {newBlogList.map((item, index) => {
            return (
              <Article
                item={item}
                delay={index > 0 ? (index - 1) * 100 : 0}
                key={index}
              />
            )
          })}
        </div>
      </section>

      {/* AI聊天组件 */}
      <AIChat isOpen={isOpenAi} onClose={() => setIsOpenAi(false)} />
      <AuthModal
        isOpen={isModalOpen}
        showLogin={true}
        onClose={() => setIsModalOpen(false)}
      />
    </div>
  )
}

export default HomePage
